package com.tarena.lbs.content.service.impl;

import com.tarena.lbs.base.protocol.exception.BusinessException;
import com.tarena.lbs.base.protocol.pager.PageResult;
import com.tarena.lbs.content.dao.mapper.ArticleMapper;
import com.tarena.lbs.content.dao.repository.ArticleESRepository;
import com.tarena.lbs.content.pojo.param.ArticleContentParam;
import com.tarena.lbs.content.pojo.po.ArticleSearchPO;
import com.tarena.lbs.content.pojo.query.ArticleQuery;
import com.tarena.lbs.content.pojo.vo.ArticleVO;
import com.tarena.lbs.content.service.ArticleService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.core.ElasticsearchOperations;
import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.geo.GeoPoint;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class ArticleServiceImpl implements ArticleService {

    @Autowired
    private ArticleESRepository articleESRepository;

    @Autowired
    private ElasticsearchOperations elasticsearchOperations; // 用于复杂查询

    @Autowired
    private ArticleMapper articleMapper;

    /**
     * 新增推文
     */
    @Override
    public void addArticle(ArticleContentParam param) throws BusinessException {
        // 参数校验
        if (!StringUtils.hasText(param.getArticleTitle())) {
            throw new BusinessException("1", "文章标题不能为空");
        }

        // 转换为ES实体
        ArticleSearchPO articlePO = new ArticleSearchPO();
        BeanUtils.copyProperties(param, articlePO);

        // 处理地理位置
        if (StringUtils.hasText(param.getLatitude()) && StringUtils.hasText(param.getLongitude())) {
            try {
                double lat = Double.parseDouble(param.getLatitude());
                double lon = Double.parseDouble(param.getLongitude());
                articlePO.setLocation(new GeoPoint(lat, lon));
            } catch (NumberFormatException e) {
                throw new BusinessException("1", "经纬度格式错误");
            }
        }

        // 补充时间
        Date now = new Date();
        articlePO.setCreateTime(now);
        articlePO.setUpdateTime(now);

        // 保存到ES - 现在应该可以工作了
        ArticleSearchPO saved = elasticsearchOperations.save(articlePO);
        System.out.println("保存成功，ID: " + saved.getId());
    }


}